'''
Created on 2010-10-11

@author: tongji@rekoo.com
'''
import os
import sys
import time

printf = lambda x : sys.stderr.write('%s\n' % x)

class HIVE_CLIENT(object):
    def __init__(self, command = None, temppath = '.', hook = None, delete = True):
        if command is None:
            raise 'please specify the hive command with its absolute path'
        self.command = command
        self.delete = delete
        self.temppath = temppath
        self.hook = hook
        
    def exe(self, hql = None):
        if hql is None:
            raise 'you must write a hql to run by hive'
        tempfile = '%s/temp_%s.log' % (self.temppath, time.time())
        command = '%s -S -e "%s" > %s' % (self.command, hql, tempfile)
        printf('HQL : %s is being processed...' % hql)
        return_code = os.system(command)
        if return_code == 0:
            printf('success !')
        else:
            printf('something bad happened .')
        
        if self.hook:
            self.hook(tempfile)
        
        if self.delete:
            printf('Deleting the temperate file')
            os.remove(tempfile)
        
        
        
        

if __name__ == '__main__':
    from hooks import *
    hive = HIVE_CLIENT(command = '/usr/local/hive/bin/hive', hook=process_user, delete = True)
    hive.exe('select * from farm_user_gameinfo limit 100')